/*
 * BankView.java
 *
 * Created on Dec 18, 2010, 12:29:25 PM
 */
package ui.report;

import com.nanosl.lib.date.JXDatePicker;
import ent.CollectionReceipt;
import ent.SaleCheque;
import ent.SaleChequePK;
import ent.SaleInvoice;
import java.awt.Color;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import javax.swing.JFrame;
import javax.swing.table.DefaultTableModel;
import util.Find;
import util.SuperView;

/**
 *
 * @author t
 */
public final class ReceivedChequeReportView extends SuperView {

    private static ReceivedChequeReportView instance = new ReceivedChequeReportView();

    public static void display() {
        instance.setVisible(true);
    }

    public static ReceivedChequeReportView getInstance() {
        return instance;
    }

    /**
     * Creates new form BankView
     */
    public ReceivedChequeReportView() {
        super();
        onLoad();
    }

    private ReceivedChequeReportView(JFrame jFrame, boolean b) {
        this();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();
        startDatePicker = new JXDatePicker();
        jLabel3 = new javax.swing.JLabel();
        totalLabel = new javax.swing.JLabel();
        endDatePicker = new JXDatePicker();
        jLabel1 = new javax.swing.JLabel();
        chequeNumberTextField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        setStatusComboBox = new javax.swing.JComboBox();
        updateButton = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        fillStatusComboBox = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("RECEIVED CHEQUE SUMMERY");

        masterTable.setAutoCreateRowSorter(true);
        masterTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "#", "Number", "Amount", "Received Date", "Banking Date", "Bank", "Invoice", "Receipt", "Customer"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        masterTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                masterTableMouseClicked(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                masterTableMouseReleased(evt);
            }
        });
        masterTable.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                masterTableKeyReleased(evt);
            }
        });
        masterScrollPane.setViewportView(masterTable);
        masterTable.getColumnModel().getColumn(0).setResizable(false);
        masterTable.getColumnModel().getColumn(0).setPreferredWidth(25);
        masterTable.getColumnModel().getColumn(0).setCellRenderer(rightAlignCell);
        masterTable.getColumnModel().getColumn(1).setResizable(false);
        masterTable.getColumnModel().getColumn(1).setPreferredWidth(100);
        masterTable.getColumnModel().getColumn(2).setResizable(false);
        masterTable.getColumnModel().getColumn(2).setPreferredWidth(75);
        masterTable.getColumnModel().getColumn(2).setCellRenderer(rightAlignCell);
        masterTable.getColumnModel().getColumn(3).setResizable(false);
        masterTable.getColumnModel().getColumn(3).setPreferredWidth(60);
        masterTable.getColumnModel().getColumn(4).setResizable(false);
        masterTable.getColumnModel().getColumn(4).setPreferredWidth(60);
        masterTable.getColumnModel().getColumn(5).setResizable(false);
        masterTable.getColumnModel().getColumn(5).setPreferredWidth(100);
        masterTable.getColumnModel().getColumn(5).setCellRenderer(rightAlignCell);
        masterTable.getColumnModel().getColumn(6).setResizable(false);
        masterTable.getColumnModel().getColumn(6).setPreferredWidth(50);
        masterTable.getColumnModel().getColumn(7).setResizable(false);
        masterTable.getColumnModel().getColumn(7).setPreferredWidth(50);
        masterTable.getColumnModel().getColumn(8).setResizable(false);
        masterTable.getColumnModel().getColumn(8).setPreferredWidth(150);

        startDatePicker.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startDatePickerActionPerformed(evt);
            }
        });

        jLabel3.setText("Banking Date:");

        totalLabel.setFont(new java.awt.Font("Tahoma", 1, 12));
        totalLabel.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        totalLabel.setText("0.00");

        endDatePicker.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                endDatePickerActionPerformed(evt);
            }
        });

        jLabel1.setText("Editing:");

        chequeNumberTextField.setEditable(false);

        jLabel2.setText("Status");

        setStatusComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Pending", "Cleared", "Returned" }));

        updateButton.setText("Update");
        updateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateButtonActionPerformed(evt);
            }
        });

        jLabel4.setText("Status:");

        fillStatusComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Pending", "Cleared", "Returned", "All" }));
        fillStatusComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fillStatusComboBoxActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(startDatePicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(endDatePicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(fillStatusComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(totalLabel))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(chequeNumberTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(setStatusComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(updateButton))
                    .addComponent(masterScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 892, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(startDatePicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(endDatePicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(totalLabel)
                    .addComponent(jLabel4)
                    .addComponent(fillStatusComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(masterScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 470, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(7, 7, 7)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(chequeNumberTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(setStatusComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(updateButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void masterTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_masterTableMouseClicked
        loadCheque();
    }//GEN-LAST:event_masterTableMouseClicked

    private void masterTableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_masterTableKeyReleased
        loadCheque();
    }//GEN-LAST:event_masterTableKeyReleased

    private void masterTableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_masterTableMouseReleased
    }//GEN-LAST:event_masterTableMouseReleased

    private void startDatePickerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startDatePickerActionPerformed
        fill();
    }//GEN-LAST:event_startDatePickerActionPerformed

    private void endDatePickerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_endDatePickerActionPerformed
        fill();
    }//GEN-LAST:event_endDatePickerActionPerformed

    private void updateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateButtonActionPerformed
        updat();
    }//GEN-LAST:event_updateButtonActionPerformed

    private void fillStatusComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fillStatusComboBoxActionPerformed
        fill();
    }//GEN-LAST:event_fillStatusComboBoxActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                ReceivedChequeReportView dialog = new ReceivedChequeReportView();
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField chequeNumberTextField;
    private org.jdesktop.swingx.JXDatePicker endDatePicker;
    private javax.swing.JComboBox fillStatusComboBox;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.swing.JComboBox setStatusComboBox;
    private org.jdesktop.swingx.JXDatePicker startDatePicker;
    private javax.swing.JLabel totalLabel;
    private javax.swing.JButton updateButton;
    // End of variables declaration//GEN-END:variables
    DefaultTableModel tableModel;
    SaleCheque saleCheque;

    private void fillTable() {
        tableModel.setRowCount(0);
        Date startDate = startDatePicker.getDate();
        Date endDate = endDatePicker.getDate();
        int fillStatus = fillStatusComboBox.getSelectedIndex();
        //ALTER TABLE `sgm`.`purchase_invoice` CHANGE COLUMN `inv_time` `inv_date` DATE NULL DEFAULT NULL  ;

        Collection<SaleCheque> saleCheques = Find.saleChequeByBankingDates(startDate, endDate);
        if (saleCheques == null) {
            setStatusMessage("No Record Found!", Color.red);
            return;
        }
        int i = 0;
        for (Iterator<SaleCheque> it = saleCheques.iterator(); it.hasNext();) {
            SaleCheque localSaleCheque = it.next();
            int chequeStatus = localSaleCheque.getStatus();
            if (fillStatus == 3 | chequeStatus == fillStatus) {
                CollectionReceipt collectionReceipt = localSaleCheque.getCollectionReceipt();
                SaleInvoice saleInvoice = collectionReceipt.getSaleInvoice();
                Object[] row = {++i,
                    localSaleCheque.getSaleChequePK().getChequeNumber(),
                    nf2d.format(localSaleCheque.getAmount()),
                    yyyy_MM_dd.format(collectionReceipt.getCollectedTime()),
                    yyyy_MM_dd.format(localSaleCheque.getBankingDate()),
                    localSaleCheque.getBank().getCode(),
                    saleInvoice.getInvNo(),
                    collectionReceipt.getReceiptNumber(),
                    saleInvoice.getCustomer().getName()};
                tableModel.addRow(row);
            }
        }
        calcTotal();
    }

    protected void onLoad() {
        initComponents();
        tableModel = (DefaultTableModel) masterTable.getModel();
    }

    @Override
    public void setVisible(boolean b) {
        super.setVisible(b);
        fill();
        clear();
    }

    private void fill() {
        fillTable();
        calcTotal();
    }

    private void calcTotal() {
        double total = 0;
        for (int i = 0; i < tableModel.getRowCount(); i++) {
            total += Double.valueOf(tableModel.getValueAt(i, 2).toString());
        }
        totalLabel.setText(nf2d.format(total));
    }

    private void loadCheque() {
        clear();
        if (tableModel.getRowCount() > 0) {
            int row = masterTable.getSelectedRow();
            String chequeNumber = tableModel.getValueAt(row, 1).toString();
            String bankCode = tableModel.getValueAt(row, 5).toString();
            String ReceiptNumber = tableModel.getValueAt(row, 7).toString();
            saleCheque = m.find(SaleCheque.class, new SaleChequePK(chequeNumber, bankCode, ReceiptNumber));
            if (saleCheque != null) {
                chequeNumberTextField.setText(chequeNumber);
            }
        }
    }

    private void updat() {
        if (saleCheque == null) {
            showError("No Cheque Selected.");
            return;
        }
        saleCheque.setStatus(setStatusComboBox.getSelectedIndex());
        if (m.update(saleCheque)) {
            setStatusMessage("Cheque " + saleCheque.getSaleChequePK().getChequeNumber() + " Updated.");
            clear();
            fill();
        }
    }

    private void clear() {
        saleCheque = null;
        chequeNumberTextField.setText("");
    }
}
